<?php

namespace hiduoke\services\upload\driver;

use hiduoke\base\BaseUpload;
use hiduoke\exception\UploadException;
use OSS\OssClient;

/**
 * 阿里云OSS上传
 * Class OSS
 */
class Oss extends BaseUpload
{
    /**
     * accessKey
     * @var mixed
     */
    protected $accessKey;

    /**
     * secretKey
     * @var mixed
     */
    protected $secretKey;

    /**
     * 句柄
     * @var \OSS\OssClient
     */
    protected $handle;

    /**
     * 空间域名 Domain
     * @var mixed
     */
    protected $storageDomain;

    /**
     * 存储空间名称  公开空间
     * @var mixed
     */
    protected $storageName;

    /**
     * COS使用  所属地域
     * @var mixed|null
     */
    protected $storageRegion;

    /**
     * 初始化
     * @param array $config
     * @return mixed|void
     */
    protected function initialize(array $config)
    {
        parent::initialize($config);
        $this->accessKey = $config['oss_access_key'] ?? null;
        $this->secretKey = $config['oss_access_key_secret'] ?? null;
        $this->storageDomain = $config['oss_domain'] ?? '';
        $this->storageName = $config['oss_bucket'] ?? null;
        $this->storageRegion = $config['oss_endpoint'] ?? null;
    }

    /**
     * 初始化oss
     * @return mixed|OssClient
     * @throws UploadException
     * @throws \OSS\Core\OssException
     */
    protected function app()
    {
        if (!$this->accessKey || !$this->secretKey) {
            throw new UploadException('secretId 和 secretKey 不能为空');
        }
        $this->handle = new OssClient($this->accessKey, $this->secretKey, $this->storageRegion);
        if (!$this->handle->doesBucketExist($this->storageName)) {
            $this->handle->createBucket($this->storageName, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
        }
        return $this->handle;
    }

    /**
     * 上传文件
     * @param string|file\UploadedFile|null $file 附件名
     * @param string|null $Stream 流内容
     * @param bool $isStream 是否为流上传
     * @return array|bool|\StdClass
     */
    public function upload($file = null, $Stream = null, $isStream = false)
    {
        // 流上传处理
        if ($isStream) {
            return $this->handleStreamUpload($Stream, $file);
        }

        // 文件上传处理（支持多种输入类型）
        $fileHandle = null;
        $fileName = null;

        if(is_string($file)){
            // 1. 字符串参数 - 从请求中获取文件
            $fileHandle = app()->request->file($file);
            $fileName = $file;
        } elseif($file instanceof \think\file\UploadedFile) {
            // 2. UploadedFile 对象 - 直接使用
            $fileHandle = $file;
            $fileName = $file->getFilename();
        } elseif(is_resource($file)) {
            // 3. 资源流 - 转换为流上传
            $streamContent = stream_get_contents($file);
            $key = $Stream ?: $this->createFileName('stream', 'tmp');
            return $this->handleStreamUpload($streamContent, $key);
        } else {
            // 4. 其他情况 - 尝试作为文件路径处理
            if ($file && file_exists($file)) {
                $fileName = basename($file);
                $mimeType = mime_content_type($file) ?: 'application/octet-stream';
                $fileHandle = new \think\file\UploadedFile($file, $fileName, $mimeType, 0);
            }
        }
        if (!$fileHandle) {
            throw new UploadException("上传配置有误");
        }
        // 格式验证
        $this->validateCheck($fileName, $fileHandle);

        $key = $this->createFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
        try {
            $filePath = $this->path . '/' . $key;
            $uploadInfo = $this->app()->uploadFile($this->storageName, $filePath, $fileHandle->getRealPath());
            if (!isset($uploadInfo['info']['url'])) {
                throw new UploadException("上传失败");
            }
            $this->fileInfo->uploadInfo = $uploadInfo;
            $this->fileInfo->filePath = $filePath;
            $this->fileInfo->fileUrl = $this->storageDomain . '/' . $filePath;
            $this->fileInfo->oldName = isset($fileHandle) ? $fileHandle->getOriginalName() : $key;
            $this->fileInfo->fileName = $key;
            return $this->fileInfo;
        } catch (UploadException $e) {
            throw new UploadException($e->getMessage());
        }
    }

    /**
     * 处理流上传
     * @param string $Stream 流内容
     * @param string|null $key 文件名
     * @return \StdClass
     */
    protected function handleStreamUpload($Stream, $key = null)
    {
        if (!$key) {
            $key = $this->createFileName('stream', 'tmp');
        }

        // 流内容验证
        $this->validateStreamContent($Stream, $key);

        $filePath = $this->path . '/' . $key;
        try {
            $uploadInfo = $this->app()->putObject($this->storageName, $key, $Stream);
            if (!isset($uploadInfo['info']['url'])) {
                throw new UploadException("流上传失败");
            }
            $this->fileInfo->uploadInfo = $uploadInfo;
            $this->fileInfo->filePath = $filePath;
            $this->fileInfo->fileUrl = $this->storageDomain . '/' . $filePath;
            $this->fileInfo->oldName = $key;
            $this->fileInfo->realName = $key;
            $this->fileInfo->fileName = $key;
            return $this->fileInfo;
        } catch (UploadException $e) {
            throw new UploadException($e->getMessage());
        }
    }

    /**
     * 验证流内容
     * @param string $Stream 流内容
     * @param string $key 文件名
     */
    protected function validateStreamContent($Stream, $key)
    {
        if ($this->validate) {
            // 验证文件大小
            $contentLength = strlen($Stream);
            if (isset($this->validate['filesize']) && $contentLength > $this->validate['filesize']) {
                throw new UploadException($this->validate_error['filesize']);
            }

            // 验证文件扩展名（从key中提取）
            if (isset($this->validate['fileExt']) && is_array($this->validate['fileExt'])) {
                $extension = pathinfo($key, PATHINFO_EXTENSION);
                if (!in_array(strtolower($extension), $this->validate['fileExt'])) {
                    throw new UploadException($this->validate_error['fileExt']);
                }
            }
        }
    }

    /**
     * 文件流上传
     * @param string $fileContent
     * @param string|null $key
     * @return bool|mixed
     */
    public function stream(string $fileContent, string $key = null)
    {
        try {
            if (!$key) {
                $key = $this->createFileName();
            }
            $uploadInfo = $this->app()->putObject($this->storageName, $key, $fileContent);
            if (!isset($uploadInfo['info']['url'])) {
                throw new UploadException("上传失败");
            }
            $this->fileInfo->uploadInfo = $uploadInfo;
            $this->fileInfo->realName = $key;
            $this->fileInfo->filePath = $this->storageDomain . '/' . $key;
            $this->fileInfo->fileName = $key;
            return $this->fileInfo;
        } catch (UploadException $e) {
            throw new UploadException($e->getMessage());
        }
    }

    /**
     * 删除资源
     * @param $key
     * @return mixed
     */
    public function delete(string $key)
    {
        try {
            return $this->app()->deleteObject($this->storageName, $key);
        } catch (UploadException $e) {
            throw new UploadException($e->getMessage());
        }
    }

    /**
     * 文件上传
     * @param string $file
     * @return array|bool|mixed|\StdClass
     */
    public function save(string $file = 'file')
    {
        return $this->upload($file);
    }

}
